import { useState, useEffect, useCallback, useRef } from 'react';

interface TypewriterOptions {
  speed?: number;
  cursor?: boolean;
  loop?: boolean;
  delay?: number;
}

export const useTypewriter = (
  text: string = '', 
  options: TypewriterOptions = {}
) => {
  const {
    speed = 50,
    cursor = true,
    loop = false,
    delay = 1000
  } = options;

  const [displayedText, setDisplayedText] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const currentIndexRef = useRef(0);
  const charactersRef = useRef<string[]>([]);
  const timerRef = useRef<NodeJS.Timeout>();
  const restartFlagRef = useRef(false); // 新增重启标记

  const startTyping = useCallback(() => {
    // 重置状态
    setIsTyping(true);
    setDisplayedText('');
    charactersRef.current = Array.from(text);
    currentIndexRef.current = 0;
    restartFlagRef.current = false;

    // 清除已有定时器
    if (timerRef.current) clearInterval(timerRef.current);

    timerRef.current = setInterval(() => {
      // 使用局部变量保证原子性操作
      const currentIndex = currentIndexRef.current;
      const characters = charactersRef.current;

      if (currentIndex < characters.length) {
        // 确保使用当前批次的字符和索引
        setDisplayedText(prev => {
          // 添加首字符保护逻辑
          const newChar = characters[currentIndex] || '';
          return currentIndex === 0 && prev === '' ? newChar : prev + newChar;
        });
        currentIndexRef.current++;
      } else {
        setIsTyping(false);
        clearInterval(timerRef.current!);
        if (loop && !restartFlagRef.current) {
          restartFlagRef.current = true;
          setTimeout(startTyping, delay);
        }
      }
    }, speed);
  }, [text, speed, loop, delay]);

  useEffect(() => {
    if (text) {
      startTyping();
    } else {
      setDisplayedText('');
      setIsTyping(false);
    }

    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [startTyping, text]);

  return {
    text: displayedText || '\u00A0',
    isTyping,
    cursor: cursor && isTyping,
  };
};